package auth;

import beans.User;
import util.Parser;

import javax.servlet.ServletContext;
import java.io.InputStream;


public class Authorisation {
    private ServletContext servletContext;
    private User user;


    public Authorisation(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    public boolean avtorization(String login, String pass) {
        return checkAndCreate(login,pass);
    }

    private boolean checkAndCreate(String login, String pass) {
        InputStream usersFileContent = servletContext.getResourceAsStream("WEB-INF/users.txt");
        StringBuffer usersData = Parser.parseFile(usersFileContent);
        String[] users = usersData.toString().split(";");
        for (String u : users) {
            if(getLogin(u).equals(login)&&getPass(u).equals(pass)){
                user = createUser(u);
                return true;
            }
        }
        return false;
    }

    private User createUser(String userData){
        return new User(getName(userData), getLogin(userData), getPass(userData), isAdmin(userData));
    }

    private String getLogin(String user){
        return user.split(",")[1];
    }

    private String getPass(String user){
        return user.split(",")[2];
    }

    private String getName(String user){
        return user.split(",")[0];
    }
    private boolean isAdmin(String user){
        return user.split(",")[3].equals("admin");
    }

    public User getUser(){
        return user;
    }
}
